﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TYAJZWeb.Models;
using TYAJZWeb.Data;
using TYAJZWeb.Utils;

namespace TYAJZWeb.Controllers
{
    public class ProjectController : BaseController
    {
        [CookiesAuthorize]
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        [CookiesAuthorize]
        public ActionResult List(ProjectSearchModel model, int page)
        {
            IQueryable<Project> r = Context.Projects.Where(t => t.IsDeleted == false).OrderByDescending(t => t.Id);

            if (!String.IsNullOrEmpty(Request.QueryString["destory"]) && Request.QueryString["destory"].ToLower() == "true")
                r = r.Where(t => t.Status == ProjectStatus.Destroyed.ToString());
            else
                r = r.Where(t => t.Status != ProjectStatus.Destroyed.ToString());

            if (!String.IsNullOrEmpty(Request.QueryString["Name"]))
                r = r.Where(t => t.Name.Contains(Request.QueryString["Name"]));

            if (!String.IsNullOrEmpty(Request.QueryString["EquipmentNO"]))
                r = r.Where(t => t.Equipment.Eq_no.Contains(Request.QueryString["EquipmentNO"]));

            if (!String.IsNullOrEmpty(Request.QueryString["EquipmentInspectNO"]))
                r = r.Where(t => t.Equipment.Eq_InspectNO.Contains(Request.QueryString["EquipmentInspectNO"]));

            if (model != null)
            {
                if (!String.IsNullOrEmpty(model.CreatedStartDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.CreatedStartDT, out tmp))
                        r = r.Where(t => t.CreateDT > tmp);
                }
                if (!String.IsNullOrEmpty(model.CreatedEndDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.CreatedEndDT, out tmp))
                        r = r.Where(t => t.CreateDT < tmp);
                }
                if (!String.IsNullOrEmpty(model.InspectStartDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.InspectStartDT, out tmp))
                        r = r.Where(t => t.InspectTime > tmp);
                }
                if (!String.IsNullOrEmpty(model.InspectEndDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.InspectEndDT, out tmp))
                        r = r.Where(t => t.InspectTime < tmp);
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["type"]))
            {
                var inspectResult = InspectResults.Pass.ToString();
                var type = Request.QueryString["type"];
                if (type == "nearlyExpire")
                {
                    r = r.Where(t => t.InspectResult == inspectResult && t.InspectTime.AddDays(365) > DateTime.Now && t.InspectTime.AddDays(335) < DateTime.Now);
                }
                else if (type == "expired")
                {
                    r = r.Where(t => t.InspectResult == inspectResult && t.InspectTime.AddDays(365) < DateTime.Now);
                }

                r = r.OrderBy(t => t.InspectTime);
            }

            var r1 = r.Select(t => (ProjectListModel)t);
            int totalCount = r1.Count();
            r1 = r1.Skip((page - 1) * PAGESIZE).Take(PAGESIZE);
            return View(new PageList<ProjectListModel>(r1, page, PAGESIZE, totalCount));
        }

        [CookiesAuthorize]
        public ActionResult Export(ProjectSearchModel model)
        {
            IQueryable<Project> r = Context.Projects.Where(t => t.IsDeleted == false).OrderByDescending(t => t.Id);

            if (!String.IsNullOrEmpty(Request.QueryString["destory"]) && Request.QueryString["destory"].ToLower() == "true")
                r = r.Where(t => t.Status == ProjectStatus.Destroyed.ToString());
            else
                r = r.Where(t => t.Status != ProjectStatus.Destroyed.ToString());

            if (!String.IsNullOrEmpty(Request.QueryString["Name"]))
                r = r.Where(t => t.Name.Contains(Request.QueryString["Name"]));

            if (!String.IsNullOrEmpty(Request.QueryString["EquipmentNO"]))
                r = r.Where(t => t.Equipment.Eq_no.Contains(Request.QueryString["EquipmentNO"]));

            if (!String.IsNullOrEmpty(Request.QueryString["EquipmentInspectNO"]))
                r = r.Where(t => t.Equipment.Eq_InspectNO.Contains(Request.QueryString["EquipmentInspectNO"]));

            if (model != null)
            {
                if (!String.IsNullOrEmpty(model.CreatedStartDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.CreatedStartDT, out tmp))
                        r = r.Where(t => t.CreateDT > tmp);
                }
                if (!String.IsNullOrEmpty(model.CreatedEndDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.CreatedEndDT, out tmp))
                        r = r.Where(t => t.CreateDT < tmp);
                }
                if (!String.IsNullOrEmpty(model.InspectStartDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.InspectStartDT, out tmp))
                        r = r.Where(t => t.InspectTime > tmp);
                }
                if (!String.IsNullOrEmpty(model.InspectEndDT))
                {
                    var tmp = DateTime.Now;
                    if (DateTime.TryParse(model.InspectEndDT, out tmp))
                        r = r.Where(t => t.InspectTime < tmp);
                }
            }

            var fileName = String.Format("截止{0}工程列表", DateTime.Now.ToString("yyyy年MM月dd日"));
            if (!String.IsNullOrEmpty(Request.QueryString["type"]))
            {
                var inspectResult = InspectResults.Pass.ToString();
                var type = Request.QueryString["type"];
                if (type == "nearlyExpire")
                {
                    fileName = String.Format("截止{0}即将过期工程", DateTime.Now.ToString("yyyy年MM月dd日"));
                    r = r.Where(t => t.InspectResult == inspectResult && t.InspectTime.AddDays(365) > DateTime.Now && t.InspectTime.AddDays(335) < DateTime.Now);
                }
                else if (type == "expired")
                {
                    fileName = String.Format("截止{0}已过期工程", DateTime.Now.ToString("yyyy年MM月dd日"));
                    r = r.Where(t => t.InspectResult == inspectResult && t.InspectTime.AddDays(365) < DateTime.Now);
                }

                r = r.OrderBy(t => t.InspectTime);
            }

            var r1 = r.Select(t => (ProjectExportModel)t);

            var fileFullPath = Server.MapPath(String.Format("~/Upload/{0}-{1}.xlsx", fileName, CurrentUserId));
            ExcelExporter.Export<ProjectExportModel>(fileFullPath, r1.ToList());
            var bytes = System.IO.File.ReadAllBytes(fileFullPath);
            System.IO.File.Delete(fileFullPath);
            return new FileContentResult(bytes, "application/vnd.ms-excel") { FileDownloadName = fileName + ".xlsx" };
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult InspectStart()
        {
            return View();
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult InspectStart(ProjectInspectStartModel model)
        {
            if (ModelState.IsValid)
            {
                Equipment equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == model.EquipmentNO && t.IsDeleted == false);
                if (equipment == null)
                {
                    //ModelState.AddModelError("Error", "未找到该编号,请核对设备编号是否正确");
                    TempData.Add("Error", "未找到该编号,请核对设备编号是否正确");
                }
                else
                {
                    if (equipment.IsDeleted == true)
                    {
                        //ModelState.AddModelError("Error", "该设备已删除，请确认设备编号是否正确");
                        TempData.Add("Error", "该设备已删除，请确认设备编号是否正确");
                    }

                    EquipmentStatus status = EquipmentStatus.Available;
                    if (Enum.TryParse<EquipmentStatus>(equipment.Eq_Status, out status))
                    {
                        switch (status)
                        {
                            case EquipmentStatus.Available:
                                //if (String.IsNullOrEmpty(equipment.Eq_InspectNO))
                                //{
                                //    //equipment.Eq_InspectNO = String.Format("{0:D5}", Context.Equipments.Count(t => t.Id < equipment.Id) + 1);
                                //    equipment.Eq_InspectNO = equipment.Eq_no;
                                //    Context.SubmitChanges();
                                //}
                                return RedirectToAction("Add", "Project", new { EquipmentNO = model.EquipmentNO });
                            case EquipmentStatus.Working:
                                TempData.Add("Error", "该设备为在用设备，请核对设备编号是否正确或该设备是否需要报拆。");
                                break;
                            case EquipmentStatus.Destoryed:
                                TempData.Add("Error", "该设备为已经报废，请核对设备编号是否正确。");
                                break;
                        }
                    }
                }
                return View();
            }
            return View(model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Add(String EquipmentNO)
        {
            Equipment equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == EquipmentNO && t.IsDeleted == false);
            if (equipment == null)
            {
                TempData.Add("Error", "未找到该编号,请核对设备编号是否正确");
                return View("InspectStart");
            }
            else
            {
                if (equipment.IsDeleted == true)
                {
                    TempData.Add("Error", "该设备已删除，请确认设备编号是否正确");
                    return View("InspectStart");
                }
                EquipmentStatus status = EquipmentStatus.Available;
                if (Enum.TryParse<EquipmentStatus>(equipment.Eq_Status, out status))
                {
                    switch (status)
                    {
                        case EquipmentStatus.Available:
                            //if (String.IsNullOrEmpty(equipment.Eq_InspectNO))
                            //{
                            //    //equipment.Eq_InspectNO = String.Format("{0:D5}", Context.Equipments.Count(t => t.Id < equipment.Id) + 1);
                            //    equipment.Eq_InspectNO = equipment.Eq_no;
                            //    Context.SubmitChanges();
                            //}
                            break;
                        case EquipmentStatus.Working:
                            TempData.Add("Error", "该设备为在用设备，请核对设备编号是否正确或该设备是否需要报拆。");
                            return View("InspectStart");
                        case EquipmentStatus.Destoryed:
                            TempData.Add("Error", "该设备为已经报废，请核对设备编号是否正确。");
                            return View("InspectStart");
                    }
                }
            }

            var companies = Context.Companies.Where(t => t.IsDeleted == false).ToList();

            ViewBag.InstallCompanies = companies.Where(t => t.CanInstall)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.LendCompanies = companies.Where(t => t.CanLend)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.ProductCompanies = companies.Where(t => t.CanProduct)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.InspectDepartments = Context.InspcetDepartments.Where(t => t.IsDeleted == false)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            //model.Equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == model.EquipmentNO);

            return View(new ProjectAddModel(Context.Equipments.SingleOrDefault(t => t.Eq_no == EquipmentNO && t.IsDeleted == false)));
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Add(ProjectAddModel model)
        {

            if (ModelState.IsValid)
            {
                Project p = (Project)model;
                p.CreateDT = DateTime.Now;
                p.ModifiedDT = DateTime.Now;
                p.LastModifiedUser = CurrentUserId;
                p.IsDeleted = false;
                p.Equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == model.EquipmentNO && t.IsDeleted == false);
                //p.EquipmentId = model.EquipmentId;
                p.Equipment.Eq_Status = EquipmentStatus.Working.ToString();
                p.Equipment.Eq_InspectNO = model.InspectNO;
                //var equipment = Context.Equipments.SingleOrDefault(t => t.Id == p.EquipmentId);
                //equipment.Eq_Status = EquipmentStatus.Working.ToString();
                Context.Projects.InsertOnSubmit(p);
                Context.SubmitChanges();
                return RedirectToAction("Detail", new { Id = p.Id });
            }

            var companies = Context.Companies.Where(t => t.IsDeleted == false).ToList();

            ViewBag.InstallCompanies = companies.Where(t => t.CanInstall)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.LendCompanies = companies.Where(t => t.CanLend)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.ProductCompanies = companies.Where(t => t.CanProduct)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            ViewBag.InspectDepartments = Context.InspcetDepartments.Where(t => t.IsDeleted == false)
                .Select(t => new SelectListItem()
                {
                    Text = t.Name,
                    Value = t.Id.ToString()
                }).ToList();

            model.Equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == model.EquipmentNO && t.IsDeleted == false);

            return View(model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult InspectResultEdit(int id)
        {
            ViewBag.InspectResults = new List<SelectListItem>
            {
                new SelectListItem(){ Text="通过", Value=InspectResults.Pass.ToString()},
                new SelectListItem(){Text="未通过", Value=InspectResults.Failure.ToString()}
            };
            return View((InspectResultEditModel)Context.Projects.SingleOrDefault(t => t.Id == id));
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult InspectResultEdit(InspectResultEditModel model)
        {
            if (ModelState.IsValid)
            {
                Project p = Context.Projects.SingleOrDefault(t => t.Id == model.Id);
                if (p != null)
                {
                    p.InspectResult = model.InspectResult;
                    p.InspectDepartment = model.InspectDepartment;
                    p.InspectTime = Convert.ToDateTime(model.InspectTime);
                    p.Status = ProjectStatus.InspectResultSuccess.ToString();
                    Context.SubmitChanges();
                    AddSuccessMsg("录入检测结果成功");
                    return RedirectToAction("Detail", new { Id = model.Id });
                }
            }
            return View(model);
        }

        [CookiesAuthorize]
        [HttpGet]
        [HandleError]
        public ActionResult Apply(int id)
        {
            Project p = Context.Projects.SingleOrDefault(t => t.Id == id);
            if (p != null)
            {
                if (p.Status == ProjectStatus.InspectResultSuccess.ToString())
                {
                    return View((ProjectApplyModel)Context.Projects.SingleOrDefault(t => t.Id == id));
                }
                else if (p.Status == ProjectStatus.ApplyFormFinish.ToString())
                {
                    return View("ZhunYunZheng");
                }
                else
                {
                    return View("Error", "项目状态为" + p.Status);
                }
            }
            return View("Error", "找不到该工程");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Apply(ProjectApplyModel model)
        {
            var project = Context.Projects.SingleOrDefault(t => t.Id == model.Id);
            if (project != null)
            {
                var driver = Context.Drivers.SingleOrDefault(t => t.CertificationNO == model.DriverNO);
                if (driver == null)
                {
                    driver = new Driver()
                    {
                        CreateDT = DateTime.Now,
                        ModifiedDT = DateTime.Now,
                        CertificationNO = model.DriverNO,
                        CategoryId = Context.Categories.SingleOrDefault(t1 => t1.Value == "司机").Id,
                        Comment = string.Empty,
                        IsDeleted = false,
                        IsWorking = true,
                        Name = model.Driver,
                        LastModifiedUser = CurrentUserId
                    };
                    Context.Drivers.InsertOnSubmit(driver);
                }
                else
                {
                    if (driver.IsWorking)
                        ModelState.AddModelError("Error", "该司机正在使用中");
                }
                var signalDriver = Context.Drivers.SingleOrDefault(t => t.CertificationNO == model.SignalDriverNO);
                if (signalDriver == null)
                {
                    signalDriver = new Driver()
                    {
                        CreateDT = DateTime.Now,
                        ModifiedDT = DateTime.Now,
                        CertificationNO = model.DriverNO,
                        CategoryId = Context.Categories.SingleOrDefault(t1 => t1.Value == "信号工").Id,
                        Comment = string.Empty,
                        IsDeleted = false,
                        IsWorking = true,
                        Name = model.Driver,
                        LastModifiedUser = CurrentUserId
                    };
                    Context.Drivers.InsertOnSubmit(signalDriver);
                }
                else
                {
                    if (driver.IsWorking)
                        ModelState.AddModelError("Error", "该信号工正在使用中");
                }
                if (ModelState.IsValid)
                {
                    project.Driver = driver;
                    project.Driver1 = signalDriver;
                    project.ConstructionPermitNO = model.ConstructionPermitNO;
                    project.Status = ProjectStatus.ApplyFormFinish.ToString();
                    project.LastModifiedUser = CurrentUserId;
                    Context.SubmitChanges();

                    TempData.Add("Success", "申领成功");
                    return RedirectToAction("ZhunYunZheng", new { Id = project.Id });
                }
            }
            return View("Apply", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult ZhunYunZheng(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            return View(new ProjectZhunYunModel(p));
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Destory(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            if (p != null)
            {
                p.Status = ProjectStatus.Destroyed.ToString();
                p.LastModifiedUser = CurrentUserId;
                if (p.Driver != null) p.Driver.IsWorking = false;
                p.Equipment.Eq_Status = EquipmentStatus.Available.ToString();
                if (p.Driver1 != null) p.Driver1.IsWorking = false;
                Context.SubmitChanges();
                TempData.Add("Success", "报拆成功");
                return RedirectToAction("List");
            }
            return View("Error");
        }

        //[CookiesAuthorize]
        //[HttpGet]
        //public ActionResult DestoryProjects()
        //{
        //    int pageSize = int.MaxValue;
        //    var r = Context.Projects.Where(t => t.IsDeleted == false)
        //        .OrderByDescending(t => t.Id)
        //        .Select(t => (ProjectListModel)t);
        //    int totalCount = r.Count();
        //    return View("List", new PageList<ProjectListModel>(r, 1, pageSize, totalCount));
        //}

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Detail(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            //return View((ProjectDetailModel)p);
            return View(new ProjectDetailModel(p));
        }

        [CookiesAuthorize]
        public ActionResult ZhunYunPrintSuccess(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            p.HasPrinted = true;
            Context.SubmitChanges();
            return new ContentResult() { Content = "true" };

        }

        [CookiesAuthorize]
        public ActionResult Search()
        {
            Dictionary<String, String> destoryied = new Dictionary<string, string>();
            destoryied.Add("All", "显示所有工程");
            destoryied.Add("True", "仅显示已报拆工程");
            destoryied.Add("False", "仅显示未报拆工程");

            ViewBag.Destory = destoryied.Select(t => new SelectListItem()
            {
                Value = t.Key,
                Text = t.Value
            });
            return View();
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Search(ProjectSearchModel model)
        {
            return RedirectToAction("List", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult PrintTags(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            return View(new ProjectTagModel(p));
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult PrintEquipmentBeiAn(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            if (p.Equipment.IsLocal)
            {
                return View("PrintEquipmentBeiAnLocal", new ProjectBeiAnPrintModel(p));
            }
            else
            {
                return View("PrintEquipmentBeiAnExternal", new ProjectBeiAnPrintModel(p));
            }
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult InspectAgain(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            return View((ProjectInspectAgainModel)p);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult InspectAgain(ProjectInspectAgainModel model)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == model.Id);
            p.InspectTime = model.InspectTime;
            Context.SubmitChanges();
            TempData.Add("Success", "续检成功");
            return RedirectToAction("Detail", new { Id = model.Id });
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Edit(int id)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == id);
            return View((ProjectEditModel)p);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Edit(ProjectEditModel model)
        {
            var p = Context.Projects.SingleOrDefault(t => t.Id == model.Id);
            p.EquipmentMobile = model.Mobile;
            p.EquipmentOwner = model.Owner;
            Context.SubmitChanges();
            AddSuccessMsg("修改成功");
            return RedirectToAction("Detail", new { Id = model.Id });
        }
    }
}
